package nl.zuiderfestival.raydance.model.net;

import java.util.Observable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import TUIO.TuioClient;
import TUIO.TuioListener;

public class RadarManager extends Observable implements Runnable {

	private static final Logger log = LoggerFactory.getLogger(RadarManager.class);

	private static final int DEFAULT_PORT = 3333;
	
	private Thread thread;
	private TuioClient client;

	private int port;

	private TuioEventTranslator l;

	public RadarManager(TuioEventTranslator l, int port) {
		super();
		this.l = l;
		this.port = port;
		init();
		
	}

	private void init() {
		client = new TuioClient(port);
		client.addTuioListener(l);
		l.addClient(client);
	}

	public RadarManager(TuioEventTranslator l) {
		this(l, DEFAULT_PORT);
	}

	public int getPort() {
		return port;
	}

	public void start() {
		thread = new Thread(this);
		thread.start();
		setChanged();
		notifyObservers();
		log.debug("Started.");
	}

	public void stop() {
		thread = null;
		client.disconnect();
		setChanged();
		notifyObservers();
		log.info("Stopped.");
	}

	public void run() {
		Thread myThread = Thread.currentThread();
		while (myThread == thread) {
			
			if (!isConnected()) {
				client.connect();
				setChanged();
				notifyObservers();
				if (!isConnected()) {
					log.debug("Port {} is in use, i'll keep trying.", new Object[] {port});
				} else {
					log.info("Listening for TUIO events on port {}.", new Object[] {port});
				}
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				stop();
			}
		}
	}

	public boolean isConnected() {
		return client.isConnected();
	}

	public void changePortTo(int port) {
		this.port = port;
		init();
	}

	public void addTuioListener(TuioListener listener) {
		client.addTuioListener(listener);
	}
	
}
